package com.jinke.api.common.retry;

import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @projectName:
 * @title: CommonRetryBuilder
 * @description: 公共请求重试builder
 * @see:
 * @author: hhp
 * @version: 1.0.0
 * @createTime: 2024/8/13 10:28
 */
@Component
public class CommonRetryBuilder {
    public Retryer build() {
        //定义重试机制
        Retryer<String> retryer = RetryerBuilder.<String>newBuilder()

                //retryIf 重试条件
                //.retryIfException()
                //.retryIfRuntimeException()
                //.retryIfExceptionOfType(Exception.class)
                //.retryIfException(Predicates.equalTo(new Exception()))
                //.retryIfResult(Predicates.equalTo(false))
                // 只有自定义needRetryException才重试 其他任何异常都不重试
                .retryIfExceptionOfType(NeedRetryException.class)

                //停止策略 : 尝试请求3次
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))

                //等待策略：每次请求间隔1s
                //fixedWait 固定X秒后重试
                //noWait不等时间直接重试
                //incrementingWait 第一个参数为第一次重试时间，后面会通过设置间隔递增秒数重
                //randomWait 随机等待设置范围内的时间重试
                .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))

                //默认的阻塞策略：线程睡眠
                //.withBlockStrategy(BlockStrategies.threadSleepStrategy())
                //自定义阻塞策略：自旋锁
                .withBlockStrategy(new SpinBlockStrategy())

                //自定义重试监听器
                .withRetryListener(new RetryLogListener())

                .build();

        return retryer;
    }
}
